package com.taptech.doufu.services.history;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import com.alibaba.fastjson.JSONArray;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.db.history.Read_DataBaseUtil;
import com.taptech.doufu.bean.base.ResponseBaseBean;
import com.taptech.doufu.event.BaseEventBusBean;
import com.taptech.doufu.event.EventBusConstant;
import com.taptech.doufu.services.personalcenter.AccountService;
import com.taptech.doufu.net.retrofit.api.ApiClient;
import com.taptech.doufu.net.retrofit.api.BaseSubscriber;
import com.taptech.doufu.net.retrofit.api.RxJavaHelper;
import com.taptech.doufu.util.sp.DiaoBaoSharedPreferences;
import org.greenrobot.eventbus.EventBus;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

public class ReadHistoryUtil {


    private final static String SP_READ_HISTORY_NEAD_UPLOAD_KEY = "read_history_need_upload_";

    public interface OnGetDataResult{
        void onNext(List<ReadRecord> list);
        void onError(Throwable e);
    }

    public interface OnPustDataResult{
        void onNext();
        void onError(Throwable e);
    }

    public interface OnStringResult{
        void onResult(String s);
    }


    /**
     * 同步数据
     */
    public static void uploadDBTable() {
        if (AccountService.getInstance().isLogin()) {
            if (DiaoBaoSharedPreferences.getSharedPreferencesValueToBoolean(SP_READ_HISTORY_NEAD_UPLOAD_KEY+AccountService.getInstance().getUserUid(),
                    WeMediaApplication.getInstance(), true)) {    //
                final Read_DataBaseUtil read_dataBaseUtil = new Read_DataBaseUtil(WeMediaApplication.applicationContext);
                if (read_dataBaseUtil.isDBTableNull()) {
                    //没有数据则从服务器拉取数据
                    getReadHistory(new OnGetDataResult() {
                        @Override
                        public void onNext(List<ReadRecord> list) {
                            if (list != null && list.size() > 0) {
                                read_dataBaseUtil.insertList(list);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                        }
                    },100,0);

                }else{
                    //如果有数据则将本地数据上传至服务器
                    remoteData(WeMediaApplication.getInstance());
                }
            }else{
                checkSycnFailData();
            }
        }


    }


    /**
     * 检查是是否有同步失败的数据
     */
    public static void checkSycnFailData() {
        if (!AccountService.getInstance().isLogin()) {
            return;
        }
        Observable.create(new Observable.OnSubscribe<JSONArray>() {
            @Override
            public void call(Subscriber<? super JSONArray> subscriber) {
                Read_DataBaseUtil read_dataBaseUtil = new Read_DataBaseUtil(WeMediaApplication.applicationContext);
                JSONArray array = read_dataBaseUtil.querySycnFailHistoryList();
                if (array != null && array.size() > 0) {
                    subscriber.onNext(array);
                }
            }
        }).flatMap(new Func1<JSONArray, Observable<ResponseBaseBean>>() {
            @Override
            public Observable<ResponseBaseBean> call(JSONArray array) {
                return ApiClient.getInstance().setUseCache(false).getService().moveReadHistory(array.toJSONString(),1);
            }
        }).compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread()).subscribe(new BaseSubscriber<ResponseBaseBean>(){
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(ResponseBaseBean responseBaseBean) {
                super.onNext(responseBaseBean);
                //将所有错误记录改成正常状态
                cleanSycnFailState();
                //更新书架轮播图
                BaseEventBusBean eventBus = new BaseEventBusBean();
                eventBus.setTag(EventBusConstant.TAG_BOOK_SHELF);
                EventBus.getDefault().post(eventBus);
            }
        });
    }


    public static void cleanSycnFailState() {
        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                Read_DataBaseUtil read_dataBaseUtil = new Read_DataBaseUtil(WeMediaApplication.applicationContext);
                read_dataBaseUtil.update(0);
            }
        }).compose(RxJavaHelper.observeOnMainThread())
        .subscribe(new BaseSubscriber<>());
    }

    /**
     * 数据迁移
     * @param context
     */
    private static void remoteData(final Context context) {

        Observable.create(new Observable.OnSubscribe<JSONArray>() {
            @Override
            public void call(Subscriber<? super JSONArray> subscriber) {
                Read_DataBaseUtil read_dataBaseUtil = new Read_DataBaseUtil(context);
                JSONArray array = read_dataBaseUtil.queryRecentHistoryList(500);
                subscriber.onNext(array);
            }
        }).flatMap(new Func1<JSONArray, Observable<ResponseBaseBean>>() {
            @Override
            public Observable<ResponseBaseBean> call(JSONArray array) {
                return ApiClient.getInstance().setUseCache(false).getService().moveReadHistory(array.toJSONString(),0);
            }
        }).compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread()).subscribe(new BaseSubscriber<ResponseBaseBean>(){
            @Override
            public void onError(Throwable e) {
                super.onError(e);
            }

            @Override
            public void onNext(ResponseBaseBean responseBaseBean) {
                super.onNext(responseBaseBean);
                DiaoBaoSharedPreferences.setSharedPreferencesValueToBoolean(SP_READ_HISTORY_NEAD_UPLOAD_KEY+AccountService.getInstance().getUserUid(),false,context);
            }
        });
    }


    public static void getReadHistory(final OnGetDataResult onGetDataResult,int size,int last) {
        ApiClient.getInstance().setUseCache(false).getService().getReadHistory(size,last)
                .compose(RxJavaHelper.<ReadRecordGson>observeOnMainThread())
                .subscribe(new BaseSubscriber<ReadRecordGson>(){
                    @Override
                    public void onNext(ReadRecordGson readRecordGson) {
                        super.onNext(readRecordGson);
                        if (readRecordGson != null && readRecordGson.getData() != null && readRecordGson.getData().getList() != null) {
                            onGetDataResult.onNext(readRecordGson.getData().getList());
                        }else{
                            onGetDataResult.onError(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        onGetDataResult.onError(e);
                    }
                });
    }

    public static void getBookshelfData(Activity activity, final OnGetDataResult onGetDataResult) {
        ApiClient.getInstance().setUseCache(false).getService().getBookshelfData()
                .compose(RxJavaHelper.<ReadRecordGson>observeOnMainThread(activity))
                .subscribe(new BaseSubscriber<ReadRecordGson>(){
                    @Override
                    public void onNext(ReadRecordGson readRecordGson) {
                        super.onNext(readRecordGson);
                        if (readRecordGson != null && readRecordGson.getData() != null && readRecordGson.getData().getList() != null) {
                            onGetDataResult.onNext(readRecordGson.getData().getList());
                        }else{
                            onGetDataResult.onError(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        onGetDataResult.onError(e);
                    }
                });
    }


    public static void addOrUpdateData(final ReadRecord model) {
        ApiClient.getInstance().setUseCache(false).getService().addOrUpdateDataReadHistory(
                model.getNovel_id(), model.getSection_id(), model.getPosition(), model.getName(),
                model.getImg_url(), model.getProgress(),model.getAll_num(), model.getType())
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread())
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        try {
                            Read_DataBaseUtil read_dataBaseUtil = new Read_DataBaseUtil(WeMediaApplication.applicationContext);
                            read_dataBaseUtil.update(model.getNovel_id(),1);
                        } catch (Exception e1) {
                        }
                    }
                });
    }

    public static void deleteData(Activity activity,String novelid, int type,final OnPustDataResult onPustDataResult) {
        ApiClient.getInstance().setUseCache(false).getService().deleteReadHistoryData(novelid,type)
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread(activity))
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                        onPustDataResult.onNext();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        onPustDataResult.onError(e);
                    }
                });
    }

    public static void deleteAllData(Activity activity,final OnPustDataResult onPustDataResult) {
        ApiClient.getInstance().setUseCache(false).getService().deleteReadHistoryAllData()
                .compose(RxJavaHelper.<ResponseBaseBean>observeOnMainThread(activity))
                .subscribe(new BaseSubscriber<ResponseBaseBean>(){
                    @Override
                    public void onNext(ResponseBaseBean responseBaseBean) {
                        super.onNext(responseBaseBean);
                        onPustDataResult.onNext();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        onPustDataResult.onError(e);
                    }
                });
    }
}
